/*
 * @Author: 橘子
 * @Date: 2023/7/9
 * @Project_description: 项目介绍
 * @Description: 代码是我抄的，不会也是真的
 */
'use strict'
const qiniu = require('qiniu');
const config = require('./config.cicd')

const mac = new qiniu.auth.digest.Mac(config.accessKey, config.secretKey);
const cdn = new qiniu.cdn.CdnManager(mac);


/**
 * @Description: 刷新文件
 * @author 橘子
 */
const refreshUrl = (urls) => {
    return new Promise((resolve, reject) => {
        cdn.refreshUrls(urls, function (err, respBody, respInfo) {
            if (err) {
                console.log("文件刷新失败!", err)
                resolve(false);
            }
            if (respInfo.statusCode === 200) {
                //输出对应刷新的链接
                console.log(`文件刷新成功!${urls.join(',')}`);
                resolve(true);
            } else {
                console.log("文件刷新失败!", respBody, respInfo);
                resolve(false);
            }
        });
    });
}


/**
 * @Description: 刷新目录
 * @author 橘子
 */
const refreshDir = (dirs) => {
    return new Promise((resolve, reject) => {
        cdn.refreshDirs(dirs, function (err, respBody, respInfo) {
            if (err) {
                console.log("目录刷新失败!", err)
                resolve(false);
            }
            if (respInfo.statusCode === 200) {
                //输出对应刷新的链接
                console.log(`目录刷新成功!${dirs.join(',')}`);
                resolve(true);
            } else {
                console.log("目录刷新失败!", respBody, respInfo);
                resolve(false);
            }
        });
    });
}

/**
 * @Description: 文件预取
 * @author 橘子
 */
const prefetchUrl = (urls) => {
    return new Promise((resolve, reject) => {
        cdn.prefetchUrls(urls, function (err, respBody, respInfo) {
            if (err) {
                console.log("文件预取失败!", err)
                resolve(false);
            }
            if (respInfo.statusCode === 200) {
                //输出对应刷新的链接
                console.log(`文件预取成功!${urls.join(',')}`);
                resolve(true);
            } else {
                console.log("文件预取失败!", respBody, respInfo);
                resolve(false);
            }
        });
    });
}

module.exports = {
    refreshDir,
    refreshUrl,
    prefetchUrl,
}
